package com.zzj.servlet;

import com.zzj.handler.UserHandler;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @Description TODO
 * @Author zzj
 * @Date 2020/8/6 17:38
 */
@WebServlet("/user/*")   //能匹配 /user   /user/login  /user/findAll.....
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取cookie，拿到cookie中的sessionid
        Cookie[] cookies = req.getCookies();
        // 遍历cookie
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                System.out.println(cookies[i].getName() + cookies[i].getValue());
            }
        }

        // 获取session
        HttpSession session = req.getSession();
        System.out.println("sessionId:"+ session.getId());

        // session常用api
        System.out.println("isNew"+session.isNew());
        System.out.println("session的生存时间"+session.getMaxInactiveInterval());
        session.setMaxInactiveInterval(1000000);
        System.out.println("session的生存时间"+session.getMaxInactiveInterval());
        //session.invalidate();  // 销毁session
        System.out.println("sessionId:"+ session.getId());

        /*/user/login*/
        String viewPath = "";  // 声明视图路径
        UserHandler userHandler = new UserHandler();
        // 获取请求url
        String url = req.getRequestURI();
        // 截取请求url：根据截取的部分确定请求的业务  login
        String handler = url.replace("/user", "").replace("/", "");
        // 调用对应的业务（UserHandler）
        if ("login".equals(handler)) {
            // 获取参数
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            // 调用的时候将session作为实参传入业务方法
            viewPath = userHandler.login(username, password,session);
        }
        // 返回视图
        if (viewPath != null && !viewPath.isEmpty()) {
            req.getRequestDispatcher(viewPath).forward(req, resp);
        }
    }
}
